<template>
  <div class="add-project">
    <div class="main">
      <div class="editor">
        <el-form :inline="true" :model="project" :rules="rules" ref="formRef">
          <el-form-item label="项目标题" prop="title">
            <el-input placeholder="请输入项目标题" v-model="project.title"></el-input>
          </el-form-item>
          <el-form-item label="标签">
            <el-select placeholder="请选择标签" @focus="getTags" @change="selectAddTag">
              <el-option
                v-for="item in tagList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <div class="tags">
              <el-tag
                style="margin-right: 5px"
                closable
                v-for="item in project.tags || []"
                :key="item.id"
                @close="handleCloseTag(item.name)"
              >
                {{ item.name }}</el-tag
              >
              <el-input
                v-if="inputVisable"
                v-model="inputTagValue"
                ref="inputRef"
                @blur="handleInputConfirm"
                @keyup.enter="handleInputConfirm"
              ></el-input>
              <el-button v-else size="small" @click="addTag">+ 新增标签</el-button>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submit(0)">提交</el-button>
          </el-form-item>
          <el-form-item>
            <el-button v-show="id == -1" type="success" @click="submit(3)">保存为草稿</el-button>
          </el-form-item>
          <el-form-item>
            <TextEditor v-model="project.content" />
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup>
import TextEditor from '@/components/TextEditor.vue'
import { nextTick, onMounted, ref } from 'vue'
import { getTagsListService } from '@/api/Tags'
import { ElMessage, ElMessageBox } from 'element-plus'
import { addProjectService, getByIdService, updateById } from '@/api/Peoject'
import { useRouter } from 'vue-router'
import { useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()
const id = route.params.id

/**
 * 传递参数
 */
const project = ref({
  status: null,
  title: '',
  content: '',
  tags: [],
})
/**
 * 修改文章数据
 */
const updateProject = ref({
  id: id,
  title: '',
  content: '',
  tags: [],
})

/**
 * 表单验证
 */
const formRef = ref()
const rules = {
  title: [
    {
      required: true,
      message: '项目标题 不能为空',
      trigger: 'blur',
    },
  ],
}

// 下拉框标签数据
const tagList = ref([])

const inputVisable = ref(false)
const inputTagValue = ref('')
const inputRef = ref()
// 下拉框选择标签数据
const selectAddTag = (value) => {
  if (project.value.tags.length <= 2) {
    const tag = tagList.value.find((item) => {
      if (item.id === value) {
        return item.name
      }
    })
    project.value.tags.push({ name: tag.name })
  } else {
    ElMessage.error('最多只可选择3个标签')
  }
}
const addTag = () => {
  inputVisable.value = true
  nextTick(() => {
    inputRef.value.input.focus()
  })
}
const handleInputConfirm = () => {
  if (inputTagValue.value.length < 2 || inputTagValue.value.length > 10) {
    ElMessage.error('标签长度在2-5之间')
    inputTagValue.value = ''
    inputVisable.value = false
    return false
  }
  if (project.value.tags.length <= 2) {
    project.value.tags.push({ name: inputTagValue.value })
    inputTagValue.value = ''
    inputVisable.value = false
  } else {
    ElMessage.error('最多只可输入3个标签')
    inputVisable.value = false
  }
}
// 删除标签
const handleCloseTag = (name) => {
  let index = -1
  for (let i = 0; i < project.value.tags.length; i++) {
    if (project.value.tags[i].name === name) {
      index = i
    }
  }
  if (index !== -1) {
    project.value.tags.splice(index, 1)
  }
}

/**
 * 提交数据
 * @param status
 */
const submit = (status) => {
  if (id === '-1') {
    console.log('新增文章')
    // 新增文章
    formRef.value.validate((valid) => {
      if (project.value.content === '<p><br></p>') {
        ElMessage.error('项目内容不能为空')
        return false
      }
      if (valid) {
        // 表单验证通过
        project.value.status = status
        console.log(project.value)
        addProjectService(project.value).then(() => {
          router.go(-1)
        })
      }
    })
  } else {
    ElMessageBox.confirm('你确认修改该文章信息吗', 'Warning', {
      type: 'warning',
      confirmButtonText: '确认',
      cancelButtonText: '取消',
    })
      .then(() => {
        updateProject.value.title = project.value.title
        updateProject.value.content = project.value.content
        updateProject.value.tags = project.value.tags
        updateById(updateProject.value).then(() => {
          router.go(-1)
        })
      })
      .catch(() => {
        ElMessage.success('取消修改')
      })
  }
}

/**
 * 获取所有标签信息
 */
const getTags = async () => {
  const { data } = await getTagsListService()
  tagList.value = data
}
const getById = async (id) => {
  if (id != -1) {
    const { data } = await getByIdService(id)
    project.value.title = data.title
    project.value.content = data.content
    project.value.tags = data.tags
  } else {
    console.log('当前是新增文章不用查询数据')
  }
}
onMounted(() => {
  getById(id)
})
</script>

<style lang="scss" scoped>
* {
  border: none !important;
}

.add-project {
  background-color: #f3f4f5;
  padding: 15px;

  .main {
    min-height: 100vh;
    padding: 20px;
    background-color: #fff;
    border-radius: 7px;

    .editor {
      :deep(.el-select__wrapper) {
        width: 150px;
      }

      .tags {
        :deep(.el-input) {
          width: 60px;
          height: 24px;
        }
      }
    }
  }
}
</style>